<template>
  <div style="height: 100%">
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.username" v-if="sys_user_view" placeholder="用户名" clearable @clear="findByPage"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="findByName" v-if="sys_user_view" size="medium" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add" size="medium" v-if="sys_user_add" icon="el-icon-plus">新增</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="el-icon-refresh-right" circle @click="findByPage"></el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <v-table :columns="columns" :data="tableData" :loading="loading" :table-operation="tableOperation"
               @findPage="findByPage">
        <template slot="operation" slot-scope="scope">
          <el-button
            v-if="sys_user_view"
          @click="handleView(scope.data.row)"
          :size="viewOperation.size || 'mini'"
          :style="{color: viewOperation.color|| ''}"
          :icon="viewOperation.icon"
          type="text">
            {{viewOperation.name}}
          </el-button>
          <el-button
            v-if="sys_user_edit"
            @click="handleEdit(scope.data.row)"
            :size="editOperation.size || 'mini'"
            :style="{color: editOperation.color|| ''}"
            :icon="editOperation.icon"
            type="text">
            {{editOperation.name}}
          </el-button>
          <el-button
            v-if="sys_user_delete"
            @click="handleDelete(scope.data.row)"
            :size="deleteOperation.size || 'mini'"
            :style="{color: deleteOperation.color|| ''}"
            :icon="deleteOperation.icon"
            type="text">
            {{deleteOperation.name}}
          </el-button>
        </template>
      </v-table>

      <el-dialog :title="title" :visible.sync="dialogFormVisible" width="40%">

        <el-form :model="userForm" label-width="80px" :rules="userFormRules" :disabled="view" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username" required>
            <el-input v-model="userForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-show="passwordVisible">
            <el-input v-model="userForm.password" placeholder="请输入密码" clearable></el-input>
          </el-form-item>
          <el-form-item label="部门" prop="deptName">
            <el-popover
              ref="popover"
              placement="bottom"
              trigger="click"
              v-model="popoverVisible"
              :disabled="view">
              <el-input
                :size="size"
                placeholder="输入关键字进行过滤"
                v-model="filterText"
                :disabled="view">
              </el-input>
              <el-tree
                :data="deptTree"
                :props=" { children: 'children', label: 'name' }"
                :filter-node-method="filterNode"
                ref="tree"
                @node-click="handleNodeClick"></el-tree>
            </el-popover>
            <el-input v-model="userForm.deptName" placeholder="请选择上级菜单" v-popover:popover :readonly="true" :disabled="view" @focus="findDeptTree"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleName" v-loadmore="loadMore">
            <el-select v-model="roleIds" multiple placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in roles"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" placeholder="请输入手机号" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="save" v-show="!view" v-if="passwordVisible">保 存</el-button>
          <el-button type="primary" @click="update" v-show="!view" v-else>修 改</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {userApi} from '../../../http/modules/user'
  import {roleApi} from "../../../http/modules/role";
  import vTable from '../../../components/table/table'
  import website from "../../../const/website";
  import {deptApi} from "../../../http/modules/dept"
  import {mapGetters} from "vuex"

  export default {
    name: "users",
    components: {
      vTable
    },
    data() {
      return {
        tableData: {
          totalSize: 0,
          content: []
        },
        pageRequest: {
          pageNum: 1,
          pageSize: 10
        },
        columns: [
          {prop: "username", label: "用户名", minWidth: 45},
          {prop: "phone", label: "手机号", minWidth: 80},
          {prop: "email", label: "邮箱", minWidth: 150},
          {prop: "deptName", label: "机构", minWidth: 85},
          {
            prop: "sysRoles", label: "角色", minWidth: 125, render(h, record) {
              let values = record.value //数据数组
              let newArr = [];
              values.forEach((value,index)=>{
                newArr.push(h('el-tag', {style: {'margin-right': '5px', 'margin-bottom': '5px'}}, value.roleName))
              })
              return h('div',newArr)
            }
          },
          {
            prop: "lockFlag", label: "状态", minWidth: 55, render(h, record) {
              if (record.value === '9') {
                return <el-tag danger>锁定</el-tag>
              } else {
                return <el-tag success>正常</el-tag>
              }
            }
          },
          {prop: "createTime", label: "创建时间", minWidth: 100},
        ],
        tableOperation: {
          operation: true
        },
        viewOperation: website.viewOperation, // 查看操作
        editOperation: website.editOperation, // 编辑操作
        deleteOperation: website.deleteOperation, // 删除操作
        searchForm: {
          username: ''
        },
        selections: [],
        dialogFormVisible: false,
        deptTree: [],
        popoverVisible: false,
        filterText: '',
        userForm: {
          username: '',
          password: '',
          deptId: '',
          deptName: '',
          email: '',
          phone: '',
          roleIds: [],
          sysRoles: []
        },
        userFormRules: {
          username: [
            {required: true, message: "请输入用户名", trigger: "blur"}
          ],
          password: [
            {required: false, message: "请输入密码", trigger: "blur"},
            {min: 4, message: "密码长度最少为4位", trigger: "blur"}
          ],
          phone: [
            {required: false, message: "请输入手机号", trigger: "blur"},
            {min: 11, max: 11, message: "手机号长度为11位", trigger: "blur"}
          ],
          email: [
            {required: false, message: "请输入邮箱", trigger: "blur"}
          ]
        },
        passwordVisible: true,
        title: '新增',
        roles: [],
        roleIds: [],
        rolePageRequest: {
          pageNum: 1,
          pageSize: 10
        },
        view: false,
        loading: true,
        size: 'mini'
      }
    },
    methods: {
      findByPage(data) {
        if (data != null) {
          this.pageRequest = data
        }
        userApi.findPage(this.pageRequest).then(data => {
          this.tableData = data.data
          this.loading = false
        }).catch(error => {
          console.log(error)
          this.$message.error('网络错误')
        })
      },
      add() {
        // 新增用户，弹出对话框
        this.dialogFormVisible = true
        this.passwordVisible = true
        this.title = '新增'
        this.findRoles()
      },
      cancel() {
        // 关闭对话框
        this.dialogFormVisible = false
      },
      save() {
        if (this.roleIds.length > 0) {
          this.roleIds.forEach(roleId => {
            let sysRole = {
              roleId: roleId
            }
            this.userForm.sysRoles.push(sysRole)
          })
        }
        // 保存新用户
        userApi.save(this.userForm).then(res => {
          this.$message.success('新增成功')
          this.dialogFormVisible = false
          this.findByPage()
        }).catch(error => {
          this.$message.error('保存失败')
        })

      },
      // handleClick(row, type) {
      //   let rows = []
      //   if (type === 'delete') {
      //     rows.push(row)
      //     this.handleDelete(rows)
      //   } else if(type === 'edit') {
      //     this.handleEdit(row)
      //   } else if(type === 'view') {
      //     this.handleView(row)
      //   }
      // },
      handleView(data) {
        // 用户信息查看
        this.findRoles()
        this.passwordVisible = false
        this.view = true
        this.dialogFormVisible = true
        this.title = '查看'
        this.userForm = data

        data.sysRoles.forEach(item => {
          this.roleIds.push(item.roleId)
        })
      },
      handleDelete(row) {
        let rows = []
        rows.push(row)
        // 删除用户
        this.$confirm('此操作将删除该用户，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delete(rows)
        }).catch(() => {
          this.$message.info('已取消删除')
        })

      },
      delete(datas) {
        let records = []
        datas.forEach(item => {
          records.push({userId: item.userId})
        })
        userApi.delete(records).then(res => {
          this.$message.success('删除成功')
          this.findByPage()
        }).catch(error => {
          this.$message.error('删除失败')
        })
      },
      handleEdit(data) {
        // 修改用户信息
        this.findRoles()
        this.passwordVisible = false
        this.dialogFormVisible = true
        this.view = false
        this.title = '编辑'
        this.userForm = data
        data.sysRoles.forEach(item => {
          this.roleIds.push(item.roleId)
        })
      },
      update() {
        let sysRoles = []
        this.roleIds.forEach(item => {
          sysRoles.push({roleId: item})
        })
        this.userForm.sysRoles = sysRoles
        userApi.update(this.userForm).then(res => {
          this.$message.success('更新成功')
        }).catch(error => {
          this.$message.error('更新失败')
        })
        this.passwordVisible = !this.passwordVisible
        this.dialogFormVisible = !this.dialogFormVisible
      },
      findByName() {
        userApi.findByName({username: this.searchForm.username}).then(res => {
          this.tableData.totalSize = res.data.length
          this.tableData.content = res.data
        }).catch(error => {

        })
      },
      selectionChange(selections) {
        this.selections = selections
      },
      clearUserForm() {
        // 清空上次新增的用户信息和编辑的用户信息
        this.userForm = {
          username: '',
          password: '',
          deptId: '',
          deptName: '',
          roleIds: [],
          email: '',
          phone: ''
        }
        this.roleIds = []
      },
      findRoles() {
        roleApi.findPage(this.rolePageRequest).then(res => {
          this.roles = res.data.content
        }).catch(error => {
          this.$message.error('角色查询失败，请稍后再试')
          console.log(error)
        })
      },

      loadMore() {
        this.rolePageRequest.pageNum++
        this.findRoles()
      },

      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      handleNodeClick(data) {
        this.userForm.deptName = data.name
        this.userForm.deptId = data.deptId
        this.popoverVisible = false
      },
      findDeptTree() {
        deptApi.findDeptTree().then(data => {
          // this.tableData = data.data
          this.deptTree = data.data
        })
      },
    },
    watch: {
      dialogFormVisible(val, oldValue) {
        if (!val) {
          this.clearUserForm()
        }
      }
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    created() {
      this.sys_user_view = this.permissions["sys:user:view"]
      this.sys_user_add = this.permissions["sys:user:add"]
      this.sys_user_edit = this.permissions["sys:user:edit"]
      this.sys_user_delete = this.permissions["sys:user:delete"]
    },
    mounted() {
      // this.findByPage(this.pageRequest)
    }
  }
</script>

<style scoped>

</style>
